//
//  WBLiveViewController.m
//  VoiceLive
//
//  Created by 凸阿滨 on 2017/10/20.
//  Copyright © 2017年 WB. All rights reserved.
//
#define OSSFille @"voice_live/head_img/"

#import "WBLiveViewController.h"
#import "LiveHeaderView.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import "LiveStreaming.h"
#import "BlackListView.h"
#import "LSLiveStreamingParaCtxConfiguration.h"
#import "BlackListData.h"
#import <AliyunOSSiOS/OSSService.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "AnyData.h"
#import <Photos/Photos.h>
#import "UIView+CustomAlertView.h"
@interface WBLiveViewController ()<LiveHeaderViewDelegate,UIImagePickerControllerDelegate>
{
    NSString *_urlStr;
    NSString *_user_id;
    LiveHeaderView *_headerView;
    UIButton *_resetLoginBtn;
    LSVideoParaCtxConfiguration* paraCtx;//推流视频参数设置
}
@property(nonatomic,strong) NSString *oss_url;   /*上传图片地址*/
@property(nonatomic,strong) OSSClient *client;
@property(nonatomic,strong) NSString *bucket;
@property(nonatomic,strong) NSMutableArray *black_list; /*黑名单模型*/
@property(nonatomic,strong) NSString *appendFile;  /*图片拼接地址 */
@property(nonatomic,strong) UIImagePickerController *imagePicker;;  /*照片选择控制器 */
//头像地址
@property(nonatomic,copy)NSString* headerImageUrl;
//推流实例
@property(nonatomic,strong) LSMediaCapture *mediaCapture;
//设置推流地址
@property(nonatomic,copy)NSString* pushUrl;
//头像路径名
@property(nonatomic,strong) NSString *head_imgFile;
@property (nonatomic, strong) WKWebView *wkWebView;

@property (nonatomic,strong) BlackListView *blackListView;
@end

@implementation WBLiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //oss初始化
    [self initOSS];
    [self creatUI];
    [self creaLiveRoom];
    [self creatListenPeople];
   
}

#pragma mark 上传阿里初始化
- (void)initOSS{
    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.allowsEditing = YES;
    _imagePicker.delegate = self;

    UFUserDefault *userInfo = [UFUserDefault shared];
    NSString *urlString = [[NetingAPI shared] urlStringWithModuleLiveTag:KUFApiOSS];
    NSString *newString = [NSString stringWithFormat:@"%@/%@",urlString,userInfo.channel_id];
    [WBNetworking  POST:newString parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        //初始化
        _bucket = responseObject[@"data"][@"bucket"];
        _oss_url = responseObject[@"data"][@"oss_url"];
        NSString *endpoint = responseObject[@"data"][@"endpoint"];
        NSString *AccessKeyId =responseObject[@"data"][@"Credentials"][@"AccessKeyId"];
        NSString *AccessKeySecret =responseObject[@"data"][@"Credentials"][@"AccessKeySecret"];
        NSString *SecurityToken =responseObject[@"data"][@"Credentials"][@"SecurityToken"];
            id<OSSCredentialProvider>credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKeyId secretKeyId:AccessKeySecret securityToken:SecurityToken];
            OSSClientConfiguration * conf = [OSSClientConfiguration new];
            conf.maxRetryCount = 3; // 网络请求遇到异常失败后的重试次数
            conf.timeoutIntervalForRequest = 30; // 网络请求的超时时间
            conf.timeoutIntervalForResource = 24 * 60 * 60; // 允许资源传输的最长时间
            _client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error-%@",error);
    }];

}


- (void)creatUI{
    //headerView
    LiveHeaderView *headerView = [LiveHeaderView creatLiveHeaderView];
    _headerView = headerView;
    _headerView.delegate = self;
    if(SCREEN_HEIGHT == 812){
        headerView.frame = CGRectMake(0, 40,SCREEN_WIDTH , 85);
    }else{
         headerView.frame = CGRectMake(0, 20,SCREEN_WIDTH , 85);
    }
   
    [self.view addSubview:headerView];
    //wkwebview
    _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headerView.frame), SCREEN_WIDTH, SCREEN_HEIGHT - 50 - CGRectGetMaxY(headerView.frame))  ];
    [self.view addSubview:_wkWebView];

}


#pragma mark UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //dismiss
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取图片名字
    //先获取asset在ALAssetsLibrary库中的url
    NSURL *imageUrl = [info valueForKey:UIImagePickerControllerReferenceURL];
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    //根据url获取asset信息, 并通过block进行回调
    [assetsLibrary assetForURL:imageUrl resultBlock:^(ALAsset *asset) {
        ALAssetRepresentation *representation = [asset defaultRepresentation];
        NSString *imageName = representation.filename;
        NSString *time = [AnyData getCurrenTimeString];
        _head_imgFile = [NSString stringWithFormat:@"%@%@",time,imageName];
        _appendFile = [NSString stringWithFormat:@"%@%@",OSSFille,_head_imgFile];
        
        OSSPutObjectRequest *put = [OSSPutObjectRequest new];
        put.bucketName = _bucket;
        put.objectKey = _appendFile;
        
        
        //取出选中的图片
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        // 方法一：异步赋值
        dispatch_async(dispatch_get_main_queue(), ^{
            _headerView.headerImage.image = image;
        });
        // 设置Content-Type，可选
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        NSString *gesiData = [AnyData contentTypeForImageData:imageData];
        
        NSString *contentType = [NSString stringWithFormat:@"image/%@",gesiData];
        put.contentType = contentType;
        put.uploadingData = imageData;
        
        OSSTask *putTask = [_client putObject:put];
        [putTask continueWithBlock:^id(OSSTask *task) {
            NSLog(@"objectKey: %@", put.objectKey);
            if (!task.error) {
                NSLog(@"upload object success!");
                [self editHeaderImage];
            } else {
                NSLog(@"upload object failed, error: %@" , task.error);
                [self alertMessage:@"上传头像失败！"];
            }
            return nil;
        }];
        
        
        
    } failureBlock:^(NSError *error) {
        NSLog(@"%@", [error localizedDescription]);
    }];
    
}

#pragma mark 通知上传头像
- (void)editHeaderImage{
    UFUserDefault *userInfo = [UFUserDefault shared];
    NSString *urlString = [[NetingAPI shared] urlStringWithModuleLiveTag:KUFEditImage];
    NSString *newString = [NSString stringWithFormat:@"%@/%@",urlString,userInfo.channel_id];
    NSString *img_url = [NSString stringWithFormat:@"%@%@",_oss_url,_head_imgFile];
    NSDictionary *parameters = @{@"channel_id":userInfo.channel_id,@"img_url":img_url};
    [WBNetworking  POST:newString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if([responseObject[@"code"] isEqualToString:@"200"]){
              [self alertMessage:@"修改头像成功！"];
        }else{
              [self alertMessage:@"修改头像失败！"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error-%@",error);
    }];

    
}


#pragma mark LiveViewDelegate
- (void)showBlackList{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
        _blackListView = [BlackListView creatBlackListView];
        _blackListView.frame = CGRectMake(0, 0, 300, 354);
       //添加弹出动画
        [_blackListView showInWindowWithMode:CustomAnimationModeAlert bgAlpha:0.5];
        _blackListView.yj_centerX = _wkWebView.yj_centerX;
        _blackListView.yj_centerY = _wkWebView.yj_centerY;
        [keyWindow addSubview:self.blackListView];
   
}


//开启直播
- (void)startLive{
    [self HUDText:@"开启直播"] ;
    [self ccreatStartLiveInfo];
}
//关闭直播
- (void)endLive{
    [self HUDText:@"关闭直播"] ;
    [_mediaCapture stopLiveStream:^(NSError *error) {
        NSLog(@"结束推流错误-%@",error);
    }];
    _mediaCapture = nil;
    
}
//选择图片
-(void)pickerHeaderImage{
    [self fetchSinglePicture];
}

#pragma mark 请求房间消息
- (void)creaLiveRoom{
    UFUserDefault *userInfo = [UFUserDefault shared];
    NSString *urlString = [[NetingAPI shared] urlStringWithModuleLiveTag:KUFLiveInfo];
    NSString *newString = [NSString stringWithFormat:@"%@/%@",urlString,userInfo.channel_id];
    NSDictionary *parameters = @{@"channel_id":userInfo.channel_id};
    [WBNetworking POST:newString parameters:parameters token:userInfo.redis_token success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
                        //头像
                        _headerImageUrl = responseObject[@"data"][@"image_url"];
                        [_headerView.headerImage sd_setImageWithURL:[NSURL URLWithString:_headerImageUrl]];
                       //房间名
                        _headerView.roomName.text = responseObject[@"data"][@"channel_name"];
                        //主播名
                        _headerView.liveerName.text = responseObject[@"data"][@"username"];
                        //user_id
                       _user_id = responseObject[@"data"][@"user_id"];
        if(_user_id.length > 0){
            NSString *chatRoomURL = [[NetingAPI shared] urlStringWithModuleLiveTag:KUFChatRoom];
            NSString *appendUrl = [NSString stringWithFormat:@"%@channel_token=%@&user_id=%@",chatRoomURL,userInfo.channel_token,_user_id];
             [_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:appendUrl]]];
            
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}

#pragma mark 请求在线收听人数
- (void)creatListenPeople{
    UFUserDefault *userInfo = [UFUserDefault shared];
    NSString *urlString = [[NetingAPI shared] urlStringWithModuleLiveTag:KUFListenPeople];
    NSString *newString = [NSString stringWithFormat:@"%@/%@",urlString,userInfo.channel_id];
    NSDictionary *parameters = @{@"channel_id":userInfo.channel_id};
    [WBNetworking POST:newString parameters:parameters token:userInfo.redis_token success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        _headerView.onlineCount.text = responseObject[@"data"];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];

    
}

#pragma mark 开始直播
- (void)ccreatStartLiveInfo{
    UFUserDefault *userInfo = [UFUserDefault shared];
    NSString *urlString = [[NetingAPI shared] urlStringWithModuleLiveTag:KUFStartLive];
    NSString *newString = [NSString stringWithFormat:@"%@/%@",urlString,userInfo.channel_id];
    NSDictionary *parameters = @{@"channel_id":userInfo.channel_id};
    [WBNetworking POST:newString parameters:parameters token:userInfo.redis_token success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //推流地址
        self.pushUrl = responseObject[@"push_url"];
       
                if(self.pushUrl.length > 0){
        
                    //设置常亮不锁屏
                    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
                    //初始化直播参数，并创建音视频直播
                    LSLiveStreamingParaCtxConfiguration *streamparaCtx = [LSLiveStreamingParaCtxConfiguration defaultLiveStreamingConfiguration];;
        
                    streamparaCtx.eOutFormatType               = LS_OUT_FMT_RTMP;
                    streamparaCtx.eOutStreamType               = LS_HAVE_AUDIO; //这里可以设置推音视频流／音频流／视频流，如果只推送视频流，则不支持伴奏播放音乐
                    streamparaCtx.uploadLog                    = YES;//是否上传sdk日志
                    streamparaCtx.sLSVideoParaCtx = paraCtx;
                    _mediaCapture = [[LSMediaCapture alloc] initLiveStream:_pushUrl withLivestreamParaCtxConfiguration:streamparaCtx];
        
                    [_mediaCapture startLiveStream:^(NSError *error) {
                                    NSLog(@"开始推流错误-%@",error);
                                }];
                }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}




#pragma mark 返回登录界面
- (void)resetAction{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"确定要退出直播?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消") ;
    }];
    UIAlertAction *quedingAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [_mediaCapture stopLiveStream:^(NSError *error) {
            NSLog(@"结束推流错误-%@",error);
        }];
        UFUserDefault *user = [UFUserDefault shared];
        user.exit = @"1";
        [user resetLoginInfos];
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alertVc addAction:cancelAction];
    [alertVc addAction:quedingAction];
    [self presentViewController:alertVc animated:YES
                     completion:nil];

    
  
    
}


@end
